package com.ruoyi.course.service.impl;

import com.aliyun.oss.OSS;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.course.domain.BusinessException;
import com.ruoyi.course.service.IOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OssServiceImpl implements IOssService {
    @Autowired
    private OSS ossClient;
    
    @Value("${oss.bucketName}")
    private String bucketName;
    
    @Value("${oss.domain}")
    private String domain;
    
    @Value("${oss.maxSize}")
    private long maxSize; // 单位：MB

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // 1. 验证文件大小（1024MB = 1024 * 1024 * 1024 bytes）
        long fileSize = file.getSize();
        long maxSizeBytes = maxSize * 1024 * 1024;
        if (fileSize > maxSizeBytes) {
            try {
                throw new BusinessException("文件大小不能超过" + maxSize + "MB");
            } catch (BusinessException e) {
                throw new RuntimeException(e);
            }
        }

        // 2. 验证文件非空
        if (file.isEmpty()) {
            try {
                throw new BusinessException("上传文件不能为空");
            } catch (BusinessException e) {
                throw new RuntimeException(e);
            }
        }

        // 3. 生成唯一文件名（避免重复）
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileSuffix;

        // 4. 按日期分组存储（如：2023/10/01/xxx.jpg）
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String key = "upload/" + datePath + "/" + fileName;

        // 5. 上传文件到OSS
        ossClient.putObject(bucketName, key, file.getInputStream());

        // 6. 返回完整访问URL
        return domain + "/" + key;
    }
}